package com.coldchain.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 获取Bean实体工具类
 **/
@Component
public class BeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(null == BeanUtils.applicationContext) {
            BeanUtils.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取Bean
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * Map转换成对象（JDK实现）
     * @param map
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T map2BeanJava(Map<String, Object> map, T t) {
        if(map == null || t == null) {
            return null;
        }

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

            for(PropertyDescriptor pd : pds) {
                String key = pd.getName();

                if(map.containsKey(key)) {
                    Object value = map.get(key);
                    Method setter = pd.getWriteMethod();
                    setter.invoke(t, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;
    }
}
